define(function(require) {

    'use strict';

    var Backbone = require('backbone'),
        $ = require('jquery'),
        Base = require('components/pop/base'),
        template = require('text!components/pop/templates/fans_tag.html');

    var utils = require('core/utils');

    require('chosen');

    return Base.extend({

        template: _.template(template),

        className: 'popover bottom',

        events: {
            'click .js-btn-cancel': 'hide',
            'click .js-btn-confirm': 'triggerCallback'
        },

        initialize: function(options) {
            Base.prototype.initialize.call(this, options);
            this.data = options.data;

            var www = _global.url.www;
            this.loadTagsUrl = www + '/fans/tag/list.json';
            this.addTagUrl = www + '/fans/tag/item.json';
            
            this.tagsData = {tags: []};
            this.loadingTags();

            var self = this;
            this.$el.on('keyup', '.chosen-choices input', function (e) {
                var $noResults = $(this).parents('.chosen-container').find('.no-results');
                if ($noResults.size() > 0 && $('.add-new-tag', this.$el).size() === 0) {
                    $noResults.append(' <div><a class="add-new-tag" href="javascript:void(0);">添加该标签</a></div>');
                }
                if (e.keyCode === 13) {
                    $('.add-new-tag', this.$el).click();
                    return false;
                }
            });

            this.$el.on('click', '.add-new-tag', function () {
                var tagName = $(this).parents('.chosen-container').find('.chosen-choices').find('input').val();
                self.createTag(tagName);
            });

        },

        createTag: function(tagName){
            var self = this;
            $.post(this.addTagUrl, {name: tagName})
                .success(function(res){
                    if(res.code == 0){
                        var data = res.data;
                        self.chosen.append("<option value="+ data.tag_id +" selected>"+ tagName +"</option>")
                            .trigger('chosen:updated');
                        utils.successNotify('创建新标签成功');
                    } else {
                        utils.errorNotify(res.msg);
                    }
                })
                .fail(function(){
                    utils.errorNotify('操作失败');
                });
        },

        loadingTags: function(){
            var self = this;
            $.get( this.loadTagsUrl, {scope: 'all'})
                .success(function(res){
                    if(res.code == 0){
                        self.tagsData.tags = res.data;
                        self.render();
                    } else {
                        utils.errorNotify(res.msg + '');
                    }
                })
                .fail(function(){
                    utils.errorNotify('数据获取失败');
                });
        },

        render: function() {
            var view = this;
            var tagsData = this.tagsData;
            var data = this.data.get();

            tagsData.tags.forEach(function(item){
                item.isSelected = data.some(function(tag){
                    return item.id == tag.id;
                });
            });
            view.$el.html(view.template(tagsData));


            this.chosen = this.$('.js-chosen-select').chosen({
                no_results_text: '木有这个标签哦'
            });
            return view;
        },

        reset: function(obj) {
            var callback = obj.callback,
                target = obj.target,
                trigger = obj.trigger,
                data = obj.data;

            this.setCallback(callback);
            this.setTarget(target);
            this.setTrigger(trigger);
            this.setData(data);
            this.positioning();
            this.show();

            this.$('.js-chosen-select').empty()
                .trigger('chosen:updated');
            this.loadingTags();
        },

        setData: function(data) {
            this.data = _.extend(this.data, data);
            this.render();
        },

        positioning: function() {
            var view = this;

            view.$el.show().position({
                of: this.target,
                my: 'center top',
                at: 'center bottom',
                collision: 'none'
            });
        },

        triggerCallback: function() {
            var view = this;

            var result = [];

            this.chosen.find(":selected").each(function() { 
                var item = $(this);
                result.push({
                    text: item.text(),
                    value: item.val()
                });
            });

            view.callback(result);
            view.hide();
        }
    });
});